/**
 * Copyright 2014,Peak Tai 台俊峰(taijunfeng_it@sina.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cenluan.kit;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.ocpsoft.prettytime.PrettyTime;
import org.ocpsoft.prettytime.units.JustNow;
import org.ocpsoft.prettytime.units.Millisecond;

/**
 * 日期工具类，用于对便捷的对日期进行一些操作
 * 
 * @author peak
 * 
 */
public class DateKit {

	private static final String DATE_PATTERN = "yyyy-MM-dd";
	private static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
	private final static PrettyTime PRETTY_TIME = new PrettyTime(Locale.CHINESE);

	static {
		PRETTY_TIME.removeUnit(JustNow.class);
		PRETTY_TIME.removeUnit(Millisecond.class);
	}

	/**
	 * 字符串转日期，自动选择转换模式
	 * 
	 * @param str
	 * @return
	 */
	public static Date toDate(String str) {
		if (str.length() == 10) {
			return toDate(str, DATE_PATTERN);
		}
		return toDate(str, DATETIME_PATTERN);
	}

	/**
	 * 日期转字符串，根据日期是否包含时间自动选择转换模式
	 * 
	 * @param date
	 * @return
	 */
	public static String toStr(Date date) {
		String str = toStr(date, DATETIME_PATTERN);
		if (str.endsWith("00:00:00")) {
			str = str.substring(0, 10);
		}
		return str;
	}

	public static Date toDate(String str, String pattern) {
		try {
			return new SimpleDateFormat(pattern).parse(str);
		} catch (ParseException e) {
			throw new IllegalArgumentException(e);
		}
	}

	public static String toStr(Date date, String pattern) {
		return new SimpleDateFormat(pattern).format(date);
	}

	/**
	 * 天数差，比较两个日期间差几天，结果保留两位小数，不分先后
	 * 
	 * @param d1
	 * @param d2
	 * @return
	 */
	public static double dayDiff(Date d1, Date d2) {
		long t1 = d1.getTime();
		long t2 = d2.getTime();
		long diffMills = t2 - t1;
		diffMills = Math.abs(diffMills);
		return new BigDecimal(diffMills).divide(
				new BigDecimal(1000 * 3600 * 24), 2, BigDecimal.ROUND_DOWN)
				.doubleValue();
	}

	public static double dayDiff(Date date) {
		return dayDiff(date, new Date());
	}

	/**
	 * 以一个好看的形式显示时间，用到prettyTime
	 * 
	 * @param date
	 * @return
	 */
	public static String prettyTime(Date date) {
		return PRETTY_TIME.format(date).replace(" ", "");
	}

}
